import { PlusCircleFilled } from "@ant-design/icons"
import { ProFormInstance } from "@ant-design/pro-components";
import { Button, Drawer, Flex, Form, FormProps, Input } from "antd";
import { useCallback, useEffect, useRef, useState } from "react";
import * as api from '../../../api';


type FieldType = {
    id?: string;
    title?: string;
    remember?: string;
};

export function AddPage() {
    const [open, setOpen] = useState(false);

    const [form] = Form.useForm();

    const showDrawer = () => {
        setOpen(true);
        form.resetFields();
    };

    const onClose = () => {
        setOpen(false);
    };

    const addPage = (values) => {
        api.addPage(values).then((res) => {
            console.log(res)
            onClose()
            const url = new URL(location.href);
            url.searchParams.set('id', res.data.data);
            location.href = url.toString();
        })
    }

    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
        console.log('Success:', values);
        addPage(values)
    };

    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    return (
        <>
            <Button onClick={showDrawer} type="text" icon={<PlusCircleFilled style={{fontSize: 22, color: '#722ed1'}}/> }></Button>
            <Drawer size='large' title="新建页面" onClose={onClose} open={open}>
                <Form
                    form={form}
                    name="basic"
                    layout='vertical'
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item<FieldType>
                        label="页面标题"
                        name="title"
                        rules={[{ required: true, message: '页面标题不能为空' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item label={null}>
                        <Flex gap="small" wrap>
                            <Button type="default" htmlType="button" onClick={onClose}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                        </Flex>
                    </Form.Item>

                </Form>
            </Drawer>
        </>
    );
}